// pages/cart/cart.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        deliveryType: 'pickup', // pickup: 自取, delivery: 外卖
        storeModalVisible: false,
        cartModalVisible: false,
        currentCategory: 0, // 当前选中的分类ID
        shoppingCart: [],
        // 分类数据
        categories: [
            { id: 0, name: '热销' },
            { id: 1, name: '推荐' },
            { id: 2, name: '新品上市' }
        ],
        shoppingCart: [],
        // 所有商品数据
        allProducts: [
            // 推荐分类的商品
            { id: 1, name: '奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 1, description: '经典原味，香浓醇厚' },
            { id: 2, name: '奶皮子酸奶（草莓味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 1, description: '新鲜草莓，酸甜可口' },
            { id: 3, name: '奶皮子酸奶（抹茶味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 1, description: '日式抹茶，清香回甘' },

            // 奶皮子酸奶分类的商品
            { id: 4, name: '经典奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 2, description: '传统工艺，纯正口感' },
            { id: 5, name: '特浓奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 2, description: '加倍浓醇，口感丰富' },
            { id: 6, name: '低脂奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 2, description: '健康低脂，轻盈无负担' },

            // 特色口味分类的商品
            { id: 7, name: '奶皮子酸奶（红枣味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 3, description: '滋补红枣，营养美味' },
            { id: 8, name: '奶皮子酸奶（蓝莓味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 3, description: '新鲜蓝莓，果香浓郁' },
            { id: 9, name: '奶皮子酸奶（芒果味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 3, description: '热带芒果，香甜爽口' },
            { id: 10, name: '奶皮子酸奶（蜜桃味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 3, description: '水蜜桃香，清新怡人' },

            // 大杯系列分类的商品
            { id: 11, name: '奶皮子酸奶（大杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 4, description: '大容量，更满足' },
            { id: 12, name: '草莓味奶皮子酸奶（大杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 4, description: '大杯草莓，双倍快乐' },
            { id: 13, name: '抹茶味奶皮子酸奶（大杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 4, description: '大杯抹茶，清新享受' },

            // 小杯系列分类的商品
            { id: 14, name: '奶皮子酸奶（小杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 7.9, quantity: 0, category: 5, description: '小巧精致，刚刚好' },
            { id: 15, name: '草莓味奶皮子酸奶（小杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 5, description: '小杯草莓，轻享美味' },
            { id: 16, name: '抹茶味奶皮子酸奶（小杯）', price: 8.9, quantity: 0, category: 5, description: '小杯抹茶，清新一刻' },

            // 新品上市分类的商品
            { id: 17, name: '奶皮子酸奶（椰子味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 6, description: '新品上市，椰香四溢' },
            { id: 18, name: '奶皮子酸奶（榴莲味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 12.9, quantity: 0, category: 6, description: '新品上市，榴莲爱好者必选' },
            { id: 19, name: '奶皮子酸奶（黑糖味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 6, description: '新品上市，黑糖香甜' },

            // 优惠套餐分类的商品
            { id: 20, name: '经典双人套餐', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 16.9, quantity: 0, category: 7, description: '原味+草莓味，超值享受' },
            { id: 21, name: '特色三人套餐', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 25.9, quantity: 0, category: 7, description: '原味+草莓+抹茶，多样选择' },
            { id: 22, name: '全家福套餐', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 35.9, quantity: 0, category: 7, description: '四种口味，尽享美味' },

            // 酸奶饮品分类的商品
            { id: 23, name: '酸奶水果捞', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 12.9, quantity: 0, category: 8, description: '新鲜水果+酸奶，健康美味' },
            { id: 24, name: '酸奶冰沙', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 11.9, quantity: 0, category: 8, description: '冰爽口感，夏日必备' },
            { id: 25, name: '酸奶昔', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 13.9, quantity: 0, category: 8, description: '绵密口感，层次丰富' },

            // 小吃搭配分类的商品
            { id: 26, name: '酸奶配麦片', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 6.9, quantity: 0, category: 9, description: '香脆麦片，营养搭配' },
            { id: 27, name: '酸奶配坚果', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 9, description: '多种坚果，口感丰富' },
            { id: 28, name: '酸奶配蜂蜜', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 5.9, quantity: 0, category: 9, description: '天然蜂蜜，甜蜜享受' }
        ],

        currentProducts: [], // 当前分类的商品列表
        totalQuantity: 0,
        totalPrice: 0
    },
    //商品分类
    GetAllCategoriesAsync() {
        return wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.GetAllCategoriesAsync", {})
    },
    // 根据分类ID获取商品
    getProductsByCategory: function (categoryId) {
        if (categoryId == 0) {
            return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetAvailableSkusAsync", {
            })
        } else if (categoryId == 1) {
            return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetAvailableSkusAsync", {
                isRecommend: true
            })
        } else if (categoryId == 2) {
            return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetSkusByIsNewAsync", {
                isNew: true
            })
        }
        else {
            return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetSkusByCategoryAsync", {
                categoryId
            })
        }

        // return this.data.allProducts.filter(product => product.category === categoryId);
    },

    // 获取当前分类名称
    getCurrentCategoryName: function () {
        const category = this.data.categories.find(cat => cat.id === this.data.currentCategory);
        return category ? category.name : '全部商品';
    },

    // 切换分类
    switchCategory: function (e) {
        const categoryId = e.currentTarget.dataset.id;
        this.getProductsByCategory(categoryId).then((res) => {
            if (res.data) {
                let newdata = this.syncProductQuantities(res.data, this.data.shoppingCart)
                this.setData({
                    currentCategory: categoryId,
                    currentProducts: newdata
                });
                // console.log(newEntityMap);
            }
        });


    },
    // 核心同步函数
    syncProductQuantities(currentProducts, shoppingCart) {
        // 创建购物车映射，便于快速查找
        const cartMap = new Map();
        if (shoppingCart.length > 0) {
            shoppingCart.forEach(cartItem => {
                const key = `${cartItem.title}|${cartItem.brand}`;
                cartMap.set(key, cartItem.quantity || 0);
            });
        }


        // 同步当前产品的数量
        currentProducts.forEach(product => {
            const key = `${product.title}|${product.brand}`;
            if (cartMap.has(key)) {
                // 如果购物车中存在相同title和brand的产品，同步quantity
                product.quantity = cartMap.get(key);
            } else {
                // 如果购物车中不存在，设置quantity为0
                product.quantity = 0;
                console.log("0000000" + product)
            }
        });

        return currentProducts;
    },
    // 切换自取/外卖
    switchType: function (e) {
        const type = e.currentTarget.dataset.type;
        this.setData({
            deliveryType: type
        });
    },

    // 显示门店信息弹窗
    showStoreModal: function () {
        this.setData({
            storeModalVisible: true
        });
    },

    // 隐藏门店信息弹窗
    hideStoreModal: function () {
        this.setData({
            storeModalVisible: false
        });
    },

    // 显示/隐藏购物车弹窗
    toggleCartModal: function () {
        if (this.data.totalQuantity === 0) return;
        this.setData({
            cartModalVisible: !this.data.cartModalVisible
        });
    },

    // 隐藏购物车弹窗
    hideCartModal: function () {
        this.setData({
            cartModalVisible: !this.data.cartModalVisible
        });
    },
    // 实体数组管理函数
    addOrUpdateEntity(existingArray, newEntity) {
        // 检查新实体是否已存在（基于name属性）
        const existingIndex = existingArray.findIndex(item => item.name === newEntity.name && item.brand === newEntity.brand);

        if (existingIndex !== -1) {
            // 如果实体已存在，quantity加1
            existingArray[existingIndex].quantity += 1;
            console.log(`实体 "${newEntity.name}" 已存在，quantity更新为: ${existingArray[existingIndex].quantity}`);
        } else {
            // 如果实体不存在，添加新实体并设置quantity为1
            const entityToAdd = {
                ...newEntity,
                quantity: 1
            };
            existingArray.push(entityToAdd);
            console.log(`新实体 "${newEntity.name}" 已添加`);
        }

        return existingArray;
    },
    // 增加商品数量
    increaseQuantity: function (e) {
        const id = e.currentTarget.dataset.id;
        const currentp = this.data.currentProducts.find(entity => entity.id === id);

        const currentProducts = this.data.currentProducts.map(item => {
            if (item.id === id) {
                item.quantity += 1;
            }
            return item;
        });
        const myshoppingCart = this.addOrUpdateEntity(this.data.shoppingCart, currentp);
        this.setData({
            // allProducts: allProducts,
            currentProducts,
            shoppingCart: myshoppingCart
            //: this.getProductsByCategory(this.data.currentCategory)
        }, () => {
            this.calculateCart();
        });
        // if (this.data.cartModalVisible) {
        //     this.setData({
        //         allProducts: allProducts,
        //         currentProducts: this.getProductsByCategory(this.data.currentCategory)
        //     }, () => {
        //         this.calculateCart();
        //     });
        // } else {
        //     this.setData({
        //         cartModalVisible: true,
        //         allProducts: allProducts,
        //         currentProducts: this.getProductsByCategory(this.data.currentCategory)
        //     }, () => {
        //         this.calculateCart();
        //     });
        // }

    },
    // 减少实体数量的函数
    decreaseEntityQuantity(existingArray, targetEntity) {
        // 查找目标实体在数组中的位置
        const existingIndex = existingArray.findIndex(item => item.name === targetEntity.name);

        if (existingIndex === -1) {
            console.log(`实体 "${targetEntity.name}" 不存在，无法减少数量`);
            return existingArray;
        }

        const currentEntity = existingArray[existingIndex];

        // 检查当前数量
        if (currentEntity.quantity <= 1) {
            // 如果数量小于等于1，从数组中移除该实体
            existingArray.splice(existingIndex, 1);
            console.log(`实体 "${targetEntity.name}" 数量为1，已从数组中移除`);
        } else {
            // 如果数量大于1，减少数量
            currentEntity.quantity -= 1;
            console.log(`实体 "${targetEntity.name}" 数量减少为: ${currentEntity.quantity}`);
        }

        return existingArray;
    },
    // 减少商品数量
    decreaseQuantity: function (e) {
        const id = e.currentTarget.dataset.id;
        const currentProducts = this.data.currentProducts.map(item => {
            if (item.id === id) {
                item.quantity -= 1;
            }
            return item;
        });
        const myshoppingCart = this.decreaseEntityQuantity(this.data.shoppingCart, currentProducts);
        // const allProducts = this.data.allProducts.map(item => {
        //     if (item.id === id && item.quantity > 0) {
        //         item.quantity -= 1;
        //     }
        //     return item;
        // });

        this.setData({
            shoppingCart: myshoppingCart,
            currentProducts
        }, () => {
            this.calculateCart();
        });
    },
    // 实体数组数量同步函数
    syncEntityQuantities(existingArray, newEntityArray) {
        // 创建新实体数组的映射，便于快速查找
        const newEntityMap = new Map();
        newEntityArray.forEach(entity => {
            newEntityMap.set(entity.quantity);
        });

        // 遍历现有数组，同步数量
        existingArray.forEach(entity => {
            if (newEntityMap.has(entity.name)) {
                // 如果新实体数组中存在相同name，同步quantity
                entity.quantity = newEntityMap.get(entity.name);
            }
        });

        return existingArray;
    },

    // 计算购物车状态
    calculateCart: function () {
        const allProducts = this.data.shoppingCart;
        let totalQuantity = 0;
        let totalPrice = 0;

        // 计算总数量和总价格
        allProducts.forEach(item => {
            totalQuantity += item.quantity;
            totalPrice += item.price * item.quantity;
        });

        // 更新数据
        this.setData({
            totalQuantity: totalQuantity,
            totalPrice: totalPrice
        });

        // 如果购物车为空，隐藏购物车弹窗
        if (totalQuantity === 0 && this.data.cartModalVisible) {
            this.setData({
                cartModalVisible: false
            });
        }
    },

    // 获取购物车中的商品
    getCartProducts: function () {
        return this.data.allProducts.filter(item => item.quantity > 0);
    },

    // 清空购物车
    clearCart: function () {
        const allProducts = this.data.currentProducts.map(item => {
            item.quantity = 0;
            return item;
        });

        this.setData({
            currentProducts: allProducts,
            shoppingCart: []
            // currentProducts: this.getProductsByCategory(this.data.currentCategory)
        }, () => {
            this.calculateCart();
        });
    },

    // 拨打电话
    makePhoneCall: function () {
        wx.makePhoneCall({
            phoneNumber: '15584918081'
        });
    },

    // 去结算
    goToCheckout: function () {
        if (this.data.totalQuantity === 0) {
            wx.showToast({
                title: '请先选择商品',
                icon: 'none'
            });
            return;
        }
        let deliveryType=this.data.deliveryType;
        wx.navigateTo({
            url: '/pages/confirm-order/confirm-order?deliveryType='+deliveryType+'&products='+JSON.stringify(this.data.currentProducts),
        })
        // 这里可以跳转到结算页面
        // wx.showModal({
        //     title: '提示',
        //     content: `共${this.data.totalQuantity}件商品，总计¥${this.data.totalPrice.toFixed(2)}，${this.data.deliveryType === 'delivery' ? '配送费¥5.00' : '到店自取'}`,
        //     confirmText: '确认下单',
        //     cancelText: '再逛逛',
        //     success: (res) => {
        //         if (res.confirm) {
        //             wx.showToast({
        //                 title: '下单成功',
        //                 icon: 'success'
        //             });
        //             // 清空购物车
        //             this.clearCart();
        //         }
        //     }
        // });
    },
    //商品分类
    GetAllCategoriesAsync() {
        return wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.GetAllCategoriesAsync", {})
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let mycategories = [
            { id: 0, name: '热销' },
            { id: 1, name: '推荐' },
            { id: 2, name: '新品上市' }
        ];
        let myshoppingCart = wx.getStorageSync('shoppingCart');
        if (myshoppingCart != "") {
            console.log("记录购物车：shoppingCart")
            this.setData({
                shoppingCart: myshoppingCart
            })
        }
        this.GetAllCategoriesAsync().then((res) => {
            if (res.data) {
                // const mergedArray = this.data.categoryList.concat(res.data);

                this.setData({
                    categories: mycategories.concat(res.data)
                })
            }
        })
        this.getProductsByCategory(0).then((res) => {
            if (res.data) {
                let newdata = this.syncProductQuantities(res.data, this.data.shoppingCart)
                this.setData({
                    currentCategory: 0,
                    currentProducts: newdata
                });
                // console.log(newEntityMap);
            }
        });
        // 页面加载时初始化数据
        // this.setData({
        //     currentProducts: this.getProductsByCategory(this.data.currentCategory)
        // });
         this.calculateCart();
    },
    sortWithRecommendTop(dataArray) {
        return dataArray.sort((a, b) => {
            // 将name为"推荐"的元素置顶
            if (a.name === "推荐") {
                return -1;
            } else if (b.name === "推荐") {
                return 1;
            }
            // 其他元素保持原有顺序
            return 0;
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log('点单页面显示');
        // 使用全局函数更新tab状态
        // app.setCurrentTab(1);
    },

    // 正确的getTabBar函数实现
    getTabBar: function () {
        // 避免递归调用，直接使用selectComponent
        const pages = getCurrentPages();
        if (pages.length === 0) return null;

        const currentPage = pages[pages.length - 1];
        return currentPage.selectComponent('#custom-tab-bar');
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

        wx.setStorageSync('shoppingCart', this.data.shoppingCart)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        wx.setStorageSync('shoppingCart', this.data.shoppingCart)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.onLoad();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})